package com.lingnan.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lingnan.dto.*;
import com.lingnan.entity.po.Company;
import com.lingnan.entity.po.CompanyHr;
import com.lingnan.entity.po.JobPosition;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.UserFeignClient;
import com.lingnan.service.HrJobPositionService;
import com.lingnan.utils.LoginContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.lingnan.service.JobPositionService;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/job")
@Validated
public class JobPositionController {

    @Autowired
    private JobPositionService jobPositionService;

    @Autowired
    private HrJobPositionService hrJobPositionService;

    @Autowired
    private UserFeignClient  userFeignClient;

    /**
     * 根据id列表获取多个职位信息
     */
    @GetMapping("getPosListByIds")
    Result<List<JobPosition>> getJobPositionByIds(@RequestParam("ids") List<Long> ids){
        List<JobPosition> jobPositionList =jobPositionService.getJobPositionByIds(ids);
        if(jobPositionList!=null && !jobPositionList.isEmpty()){
            return Result.ok(jobPositionList);
        }else {
            return Result.fail("没有获取得到职位信息");
        }

    }

    /**
     * 分页条件查询职位信息
     * @param pageNum
     * @param pageSize
     * @param queryParam
     * @return
     */
    @PostMapping("/list")
    public Result<IPage<JobPositionPageDto>> list(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestBody(required = false) JobPositionQueryParam queryParam) {

        IPage<JobPositionPageDto> result = jobPositionService.getListByQueryParam(
                pageNum,
                pageSize,
                queryParam
        );
        return Result.ok(result);
    }

    /**
     * 发布/编辑职位(完全权限)
     */
    @PostMapping("/save")
    public Result<JobPositionPageDto> saveJobPosition(@RequestBody @Valid JobPositionSaveParam saveParam) {
        JobPositionPageDto result = jobPositionService.saveJobPosition(saveParam);
        return Result.ok(result);
    }

    /**
     * 根据ID获取职位详情（用于编辑页面回显）
     */
    @GetMapping("/{id}")
    public Result<JobPositionPageDto> getJobPositionById(@PathVariable("id") Long id) {
        JobPositionPageDto result = jobPositionService.getJobPositionById(id);
        return Result.ok(result);
    }

    /**
     * 删除职位(完全权限)
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteJobPosition(@PathVariable("id") Long id) {
        jobPositionService.deleteJobPosition(id);
        return Result.ok();
    }

    /**
     * 批量删除职位(完全权限)
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteJobPosition(@RequestBody List<Long> ids) {
        jobPositionService.batchDeleteJobPosition(ids);
        return Result.ok();
    }

    /**
     * 更新职位状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateJobPositionStatus(@PathVariable("id") Long id,
                                                @RequestParam("status") Integer status) {
        jobPositionService.updateJobPositionStatus(id, status);
        return Result.ok();
    }


    /**
     * HR创建职位信息
     */
    @PostMapping("hr/create")
    public Result<JobPositionPageDto> createJobPosition(
            @RequestBody @Valid HrCreateJobPositionParam createParam) {
        // 从请求中获取当前HR的ID和公司ID（实际项目中可能从JWT或session中获取）
        Long currentHrId = getCurrentHrId();
        Long currentCompanyId = getCurrentCompanyId();

        JobPositionPageDto result = hrJobPositionService.createJobPosition(
                createParam, currentHrId, currentCompanyId);
        return Result.ok(result);
    }

    /**
     * HR获取自己创建的职位列表
     */
    @PostMapping("hr/my-positions")
    public Result<IPage<JobPositionPageDto>> getMyPositions(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestBody(required = false) JobPositionQueryParam queryParam,
            HttpServletRequest request) {


        Long currentHrId = getCurrentHrId();
        IPage<JobPositionPageDto> result = hrJobPositionService.getHrPositions(
                pageNum, pageSize, queryParam, currentHrId);

        return Result.ok(result);
    }

    /**
     * HR根据职位id和hrId编辑自己的职位
     */
    @PutMapping("hr/update/{id}")
    public Result<JobPositionPageDto> updateMyJobPosition(
            @PathVariable("id") Long id,
            @RequestBody @Valid HrCreateJobPositionParam updateParam,
            HttpServletRequest request) {
        Long currentHrId = getCurrentHrId();

        JobPositionPageDto result = hrJobPositionService.updateHrJobPosition(
                id, updateParam, currentHrId);

        return Result.ok(result);
    }

    /**
     * HR据职位id和hrId删除自己的职位
     */
    @DeleteMapping("hr/delete/{id}")
    public Result<Void> deleteMyJobPosition(@PathVariable("id") Long id, HttpServletRequest request) {

        Long currentHrId = getCurrentHrId();
        hrJobPositionService.deleteHrJobPosition(id, currentHrId);

        return Result.ok();
    }

    /**
     * HR获取自己职位的投递统计
     */
    @GetMapping("hr/statistics")
    public Result<HrJobStatisticsDto> getJobStatistics(HttpServletRequest request) {
        Long currentHrId = getCurrentHrId();
        HrJobStatisticsDto result = hrJobPositionService.getHrJobStatistics(currentHrId);
        return Result.ok(result);
    }

    // 辅助方法，从本地线程变量中获取
    private Long getCurrentHrId() {
        // 这里应该从认证信息中获取当前HR的ID
        String loginId = LoginContextHolder.getLoginId();
        Result<CompanyHr> companyHr = userFeignClient.getHrByUserId(Long.valueOf(loginId));
        return companyHr != null ? companyHr.getData().getId() : null;
    }
    private Long getCurrentCompanyId() {
        // 获取当前HR所属的公司ID
        String loginId = LoginContextHolder.getLoginId();
        Company companyByHrUserId = userFeignClient.getCompanyByHrUserId(Long.valueOf(loginId)).getData();
        String companyId = companyByHrUserId != null ? companyByHrUserId.getId().toString() : null;
        return Long.valueOf(companyId);
    }
    /**
     * 获取所有的职位信息及其数量
     */
    @GetMapping("/job-type-counts")
    public Result<Map<String, Integer>> getJobTypeCounts() {
        Map<String, Integer> counts = jobPositionService.getAllJobTypeCounts();
        return Result.ok(counts);
    }

    /**
     * 获取职位类型百分比
     */
    @GetMapping("job-type-percentages")
    public Result<Map<String, Double>> getJobTypePercentages(){
        Map<String, Double> percentages = jobPositionService.getJobTypePercentages();
        return Result.ok(percentages);
    }

}
